package com.gitee.neuray.security.gateway.filter;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.gitee.neuray.security.admin.authority.PermissionElementDto;
import com.gitee.neuray.security.auth.client.config.ServiceAuthConfig;
import com.gitee.neuray.security.auth.client.config.SysAuthConfig;
import com.gitee.neuray.security.auth.client.config.UserAuthConfig;
import com.gitee.neuray.security.auth.client.jwt.ServiceAuthUtil;
import com.gitee.neuray.security.auth.common.util.jwt.IJWTInfo;
import com.gitee.neuray.security.common.context.BaseContextHandler;
import com.gitee.neuray.security.common.msg.auth.TokenErrorResponse;
import com.gitee.neuray.security.common.util.ExceptionCommonUtil;
import com.gitee.neuray.security.gateway.config.GateWayLog;
import com.gitee.neuray.security.gateway.config.ZuuljwtUser;
import com.gitee.neuray.security.gateway.feign.IUserServiceFeignClient;
import com.gitee.neuray.security.gateway.strategy.AbstratePermissionStrategy;
import com.gitee.neuray.security.gateway.strategy.InterfaceWhiteListStrategy;
import com.gitee.neuray.security.gateway.utils.GateWayResponseUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 网关核心权限拦截类
 *
 * @author 协同设计小组
 * @create 2017-06-23 8:25
 */
@Component
@Slf4j
public class AdminAccessFilter extends ZuulFilter {
    @Autowired
    @Lazy
    private IUserServiceFeignClient userService;

    @Value("${zuul.prefix}")
    private String zuulPrefix;

    @Autowired
    private ServiceAuthConfig serviceAuthConfig;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    private ServiceAuthUtil serviceAuthUtil;
    @Autowired
    private SysAuthConfig sysAuthConfig;
    @Autowired
    private AbstratePermissionStrategy permission;
    @Autowired
    private GateWayLog gateWayLog;
    @Autowired
    private InterfaceWhiteListStrategy whiteListStrategy;
    @Autowired
    private ZuuljwtUser zuuljwtUser;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        final String requestUri = request.getRequestURI().substring(zuulPrefix.length());
        BaseContextHandler.setToken(null);
        //验证权限过程
        //接口白名单校验
        if (whiteListStrategy.isStartWith(requestUri)) {
            if(request.getHeader(userAuthConfig.getTokenHeader()) != null){
                ctx.addZuulRequestHeader("token",
                        request.getHeader(userAuthConfig.getTokenHeader()));
            }
            return null;
        }
        IJWTInfo user = null;
        try {
            user = zuuljwtUser.getJWTUser(request, ctx);
        } catch (Exception e) {
            GateWayResponseUtils.setFailedRequest(JSON.toJSONString(new TokenErrorResponse(e.getMessage())), 200);
            return null;
        }
        //如果为超级管理员，则干直接通过
        if(Objects.equals(user.getUniqueName(),sysAuthConfig.getSysUsername())){
            gateWayLog.setCurrentUserInfo(ctx,user);
            return null;
        }
        //根据用户id获取资源列表，包括菜单和菜单功能
        List<PermissionElementDto> permissionInfos = null;
        try {
            permissionInfos = userService.getPermissionByUserId(user.getId());
            PermissionElementDto element = permission.checkout(permissionInfos, ctx);
            //设置网关日志
            gateWayLog.setCurrentUserInfoAndLog(ctx,user,element);
            // 申请客户端密钥头，加到header里传递到下方服务
            ctx.addZuulRequestHeader(serviceAuthConfig.getTokenHeader(), serviceAuthUtil.getClientToken());
        } catch (Exception e) {
            log.error(ExceptionCommonUtil.getExceptionMessage(e));
            permission.sendZuulResponseError("网关异常,"+ ExceptionUtil.getMessage(e),500);
        }
        return null;
    }
}
